package com.weng.coder.service.convertor.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

/**
 *
 * @author weng
 */
@Service
@Slf4j
public class DirConvertor extends JConvertor {

    private String dir;

    public DirConvertor() {
        super();
    }

    @Override
    public File convert(File from, File to, String code, String name) throws IOException {
        try {
            //override from & to
            String dirName = System.getProperty("java.io.tmpdir");
            from = new File(dirName, "base-" + System.currentTimeMillis());
            to = new File(dirName, code + "-" + System.currentTimeMillis());

            //checkout svn to temp folder
            log.debug("copy base project from " + this.dir);
            FileUtils.copyDirectoryToDirectory(new File(this.dir), new File(dirName));
            new File(new File(dirName), new File(this.dir).getName()).renameTo(from);

            //do convert
            log.debug("convert the code to " + to);
            super.convert(from, to, code, name);

            //zip the to folder
            File out = new File(dirName, code + ".zip");
            log.debug("zip the source code. " + out);
            if (out.exists()) {
                FileUtils.deleteQuietly(out);
            }
            try( ZipOutputStream stream = new ZipOutputStream(new FileOutputStream(out));){
							Collection<File> files = FileUtils.listFiles(to, null, true);
							for (File file : files) {
								ZipEntry entry = new ZipEntry(file.getAbsolutePath().replace(to.getAbsolutePath(), ""));
								stream.putNextEntry(entry);
								stream.write(IOUtils.toByteArray(new FileInputStream(file)), 0, (int) file.length());
								stream.closeEntry();
								log.debug("zip the source code. " + entry.getName());
							}
						}catch (Exception e){
            	log.error(e.getMessage(),e);
						}



            return out;

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new IOException(e);
        }
    }

    public void setDir(String dir) {
        this.dir = dir;
    }
}
